package com.example.phoneshop.controller;

import com.example.phoneshop.controller.admin.AdminOrderController;
import com.example.phoneshop.entity.*;
import com.example.phoneshop.service.OrderService;
import com.example.phoneshop.tool.Check;
import com.example.phoneshop.tool.ResultJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


/**
 * @author nozomi
 * @date 2018/7/8 10:29
 * @description 订单控制器
 */
@Controller
public class OrderController {
    private OrderService orderService;

    @Autowired
    public OrderController(OrderService orderService) {
        this.orderService = orderService;
    }

    /**
     * 从session中获取用户
     *
     * @return
     */
    private static User getSessionUser(HttpSession session) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) ra).getRequest();
        session = request.getSession();
        return (User) session.getAttribute("user");
    }

    @RequestMapping("/order")
    public ModelAndView order() {
        return new ModelAndView("orders/order");
    }

    /**
     * 下单
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/addOrder", method = RequestMethod.POST)
    public @ResponseBody
    ResultJson addOrder(@RequestParam String username, @RequestParam String address,
                        @RequestParam String receiveName, @RequestParam String userPhone) {

        Order order = new Order();
        order.setUsername(username);
        order.setAddress(address);
        order.setReceiveName(receiveName);
        order.setUserPhone(userPhone);
        order.setOrderState("待付款");
        order.setOrderTime(System.currentTimeMillis());
        ResultJson resultJson = new ResultJson();
        orderService.addOrder(order);
        resultJson.setText("success");
        return resultJson;
    }

    /**
     * 添加收货地址
     *
     * @param address
     * @param session
     */
    @RequestMapping(value = "/addAddress", method = RequestMethod.POST)
    public String addAddress(Address address, HttpSession session) {
        User user = getSessionUser(session);
        String username = user.getUsername();
        address.setUserName(username);
        if (orderService.selectAddrByName(username) == null) {
            orderService.addAddress(address);
        } else {
            orderService.updateAddress(address);
        }
        return "order1";
    }

    /**
     * 获取收货地址
     *
     * @param address
     * @param session
     * @return
     */
    @RequestMapping(value = "/getAddress", method = RequestMethod.GET)
    public ModelAndView getAddress(Address address, HttpSession session, HttpServletResponse response) {
        if (!Check.checkLogin(session)) {
            return new ModelAndView("login/index");
        }
        User user = getSessionUser(session);
        address = orderService.selectAddrByName(user.getUsername());
        ModelAndView mv = new ModelAndView("orders/order");
        mv.addObject("address", address);
        return mv;
    }

    /**
     * 暴露attribute给视图(供th:object绑定)
     *
     * @return
     */
    @ModelAttribute("addressForm")
    public Address address() {
        return new Address();
    }

    /**
     * 根据id查找订单
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/getOneOrder", method = RequestMethod.POST)
    public ModelAndView getOrderById(@RequestParam int id) {
        ModelAndView mv = new ModelAndView("orders/order_info");
        Order order = orderService.selectById(id);
        mv.addObject("order", order);
        return mv;
    }

    /**
     * 查看我的订单
     *
     * @param session
     * @param response
     * @param username
     * @return
     */
    @RequestMapping(value = "/myOrders", method = RequestMethod.GET)
    public ModelAndView getOrderList(HttpSession session, HttpServletResponse response, String username) {
        if (AdminOrderController.isAdminLogin(session, response)) {
            return null;
        }
        ModelAndView model = new ModelAndView("orders/myOrders");
        User user = getSessionUser(session);
        username = user.getUsername();
        List<Order> list = orderService.getMyOrders(username);
        getFormatTime(list);
        model.addObject("myOrder", list);
        return model;
    }

    @RequestMapping(value = "/payment", method = RequestMethod.GET)
    public @ResponseBody
    ResultJson payment(@RequestParam("id") int id) {
        ResultJson resultJson = new ResultJson();
        Order order = orderService.selectById(id);
        String state = "已付款";
        if (state.equals(order.getOrderState())) {
            resultJson.setText("该订单已经付款");
        } else {
            order.setOrderState("已付款");
            orderService.updateState(order);
            resultJson.setText("ok");
        }

        return resultJson;
    }

    @RequestMapping(value = "/takeDeliver", method = RequestMethod.GET)
    public @ResponseBody
    ResultJson takeGoods(@RequestParam("id") int id) {
        ResultJson resultJson = new ResultJson();
        Order order = orderService.selectById(id);
        String state = "已收货";
        if (state.equals(order.getOrderState())) {
            resultJson.setText("该订单已经收货");
        } else {
            order.setOrderState("已收货");
            orderService.updateState(order);
            resultJson.setText("ok");
        }

        return resultJson;
    }

    public static void getFormatTime(List<Order> list) {
        list.forEach(order -> {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Long timestamp = order.getOrderTime();
            Date date = new Date(timestamp);
            String str = format.format(date);
            order.setDateFormatTime(str);
        });
    }
}
